//
//  YTRNYTImagePicker.m
//  testDemos
//
//  Created by royce on 2019/2/26.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "RNYTImagePicker.h"

#import "YTImagePickerController.h"
#import "YTImageManager.h"
#import "YTNSDictionary+SafeConvert.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <React/RCTUtils.h>
#import "IJSImagePickerController.h"
#import "IJSImageManager.h"
#import "IJSExtension.h"
#import "IJSMapViewModel.h"
#import <IJSFoundation/IJSFoundation.h>
#import <Photos/Photos.h>
#import "IJSVideoManager.h"
#import "IJSAlbumModel.h"
#import "ImageUriHandler.h"
#import "IJSImageManagerController.h"
@interface RNYTImagePicker ()

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) NSDictionary *cameraOptions;
/**
 保存Promise的resolve block
 */
@property (nonatomic, copy) RCTPromiseResolveBlock resolveBlock;
/**
 保存Promise的reject block
 */
@property (nonatomic, copy) RCTPromiseRejectBlock rejectBlock;
/**
 保存回调的callback
 */
@property (nonatomic, copy) RCTResponseSenderBlock callback;
/**
 保存选中的图片数组
 */
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@end

@implementation RNYTImagePicker

- (instancetype)init {
  self = [super init];
  if (self) {
    _selectedAssets = [NSMutableArray array];
  }
  return self;
}

- (void)dealloc {
  _selectedAssets = nil;
}

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(showImagePicker:(NSDictionary *)options
                  callback:(RCTResponseSenderBlock)callback) {
  self.cameraOptions = options;
  self.callback = callback;
  self.resolveBlock = nil;
  self.rejectBlock = nil;
  [self openImagePicker];
}
//
//RCT_REMAP_METHOD(asyncShowImagePicker,
//                 options:(NSDictionary *)options
//                 resolver:(RCTPromiseResolveBlock)resolve
//                 rejecter:(RCTPromiseRejectBlock)reject) {
//  self.cameraOptions = options;
//  self.resolveBlock = resolve;
//  self.rejectBlock = reject;
//  self.callback = nil;
//  [self openImagePicker];
//}

RCT_EXPORT_METHOD(openCamera:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback) {
  self.cameraOptions = options;
  self.callback = callback;
  self.resolveBlock = nil;
  self.rejectBlock = nil;
  [self takePhoto];
}

RCT_EXPORT_METHOD(deleteCache) {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  [fileManager removeItemAtPath: [NSString stringWithFormat:@"%@ImageCaches", NSTemporaryDirectory()] error:nil];
}

RCT_EXPORT_METHOD(removePhotoAtIndex:(NSInteger)index) {
  if (self.selectedAssets && self.selectedAssets.count > index) {
    [self.selectedAssets removeObjectAtIndex:index];
  }
}

RCT_EXPORT_METHOD(removeAllPhoto) {
  if (self.selectedAssets) {
    [self.selectedAssets removeAllObjects];
  }
}

// openVideoPicker
//RCT_EXPORT_METHOD(openVideoPicker:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback) {
//  [self openTZImagePicker:options callback:callback];
//}



- (void)openImagePicker{
  // 照片最大可选张数
  NSInteger imageCount = [self.cameraOptions sy_integerForKey:@"imageCount"];
  IJSImagePickerController *imageVc = [[IJSImagePickerController alloc] initWithMaxImagesCount:imageCount columnNumber:4];
  //  配置
  BOOL canEdit          = [self.cameraOptions sy_boolForKey:@"canEdit"];
  BOOL pickingOriginal  = [self.cameraOptions sy_boolForKey:@"pickingOriginal"];
  NSInteger minW      = [self.cameraOptions sy_integerForKey:@"minPhotoWidthSelectable"];
  NSInteger minH      = [self.cameraOptions sy_integerForKey:@"minPhotoHeightSelectable"];
  
  imageVc.sortAscendingByModificationDate = NO;
  imageVc.allowPickingVideo = NO;
  imageVc.allowPickingImage = YES;
  imageVc.isHiddenEdit = canEdit;
  imageVc.allowPickingOriginalPhoto = pickingOriginal;
  imageVc.hiddenOriginalButton = !pickingOriginal;
  imageVc.minImagesCount = 1;
  imageVc.networkAccessAllowed = YES;
  imageVc.minPhotoWidthSelectable = minW;
  imageVc.minPhotoHeightSelectable = minH;

  // 获取数据的方法
  [imageVc loadTheSelectedData:^(NSArray<UIImage *> *photos, NSArray *avPlayers, NSArray *assets, NSArray<NSDictionary *> *infos, IJSPExportSourceType sourceType,NSError *error) {
    
    if (sourceType == IJSPImageType)
    {
      
      NSMutableArray *result = [NSMutableArray array];
      [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *temp = [ImageUriHandler handleImageData:obj quality:[self.cameraOptions sy_integerForKey:@"quality"]];
        [result addObject:temp];
      }];
      [self invokeSuccessWithResult:result];
      [imageVc dismissViewControllerAnimated:YES completion:nil];
      NSLog(@"完成选择");
    }
  }];
  
  
  
  
  [imageVc cancelSelectedData:^{
    NSLog(@"--------取消选择----------");
  }];
  
  [[self topViewController] presentViewController:imageVc animated:YES completion:nil];
  
}

- (UIImagePickerController *)imagePickerVc {
  if (_imagePickerVc == nil) {
    _imagePickerVc = [[UIImagePickerController alloc] init];
    _imagePickerVc.delegate = self;
  }
  return _imagePickerVc;
}

#pragma mark - UIImagePickerController
- (void)takePhoto {
  AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
    // 无相机权限 做一个友好的提示
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
    [alert show];
  } else if (authStatus == AVAuthorizationStatusNotDetermined) {
    // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
      if (granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
          [self takePhoto];
        });
      }
    }];
    // 拍照之前还需要检查相册权限
  } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
    [alert show];
  } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
    [[YTImageManager manager] requestAuthorizationWithCompletion:^{
      [self takePhoto];
    }];
  } else {
    [self pushImagePickerController];
  }
}

// 调用相机
- (void)pushImagePickerController {
  UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
  if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
    self.imagePickerVc.sourceType = sourceType;
    [[self topViewController] presentViewController:self.imagePickerVc animated:YES completion:nil];
  } else {
    NSLog(@"模拟器中无法打开照相机,请在真机中使用");
  }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  [picker dismissViewControllerAnimated:YES completion:^{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
      
  
      
      UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
      
      dispatch_async(dispatch_get_main_queue(), ^{
        IJSImageManagerController *managerVc = [[IJSImageManagerController alloc] initWithEditImage:image];
        [managerVc loadImageOnCompleteResult:^(UIImage *image, NSURL *outputPath, NSError *error) {
          NSLog(@"%@",image);
          if (image) { //[self.cameraOptions sy_integerForKey:@"quality"];
            [self invokeSuccessWithResult:@[[ImageUriHandler handleImageData:image quality:[self.cameraOptions sy_integerForKey:@"quality"]]]];
          }
        }];
         [[self topViewController] presentViewController:managerVc animated:YES completion:nil];
      });

    }
  }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  [self invokeError];
  if ([picker isKindOfClass:[UIImagePickerController class]]) {
    [picker dismissViewControllerAnimated:YES completion:nil];
  }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
  }
}


- (void)invokeSuccessWithResult:(NSArray *)photos {
  if (self.callback) {
    self.callback(@[[NSNull null], photos]);
    self.callback = nil;
  }
  if (self.resolveBlock) {
    self.resolveBlock(photos);
    self.resolveBlock = nil;
  }
}

- (void)invokeError {
  if (self.callback) {
    self.callback(@[@"取消"]);
    self.callback = nil;
  }
  if (self.rejectBlock) {
    self.rejectBlock(@"", @"取消", nil);
    self.rejectBlock = nil;
  }
}

+ (BOOL)requiresMainQueueSetup
{
  return YES;
}


- (UIViewController *)topViewController {
  UIViewController *rootViewController = RCTPresentedViewController();
  return rootViewController;
}

- (dispatch_queue_t)methodQueue {
  return dispatch_get_main_queue();
}

@end


